import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_ui/src/components/ListItem.dart';
import 'package:flutter_ui/src/theme/colors.dart';

import '../FormCreator.dart';

class FormDatePicker extends StatefulWidget {
  final FormControlContext controlContext;
  FormDatePicker({Key key, this.controlContext}) : super(key: key);

  _FormDatePickerState createState() => _FormDatePickerState();
}

class _FormDatePickerState extends State<FormDatePicker> {
  DateTime pickDate;
  _pickDate(DateTime value) {
    FormCreatorHandler formHandler = FormCreatorState.of(context);
    formHandler.changeValue(widget.controlContext.copyWith(context: context, value: value?.millisecondsSinceEpoch));
  }

  Future<DateTime> _showDatePicker(context, DateTime currentValue) async {
    pickDate = currentValue;
    return showModalBottomSheet<DateTime>(
      builder: (BuildContext _context) {
        return 
        Column(
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                FlatButton(
                  child: Text("取消", style: TextStyle(color: DescColor)), 
                  onPressed: () {
                     Navigator.pop(context, currentValue);
                  }
                ),
                FlatButton(
                  child: Text("确定", style: TextStyle(color: PrimaryColor)), 
                  onPressed: () {
                    Navigator.pop(context, pickDate);
                  },
                )
              ]
            ),
            Expanded(
              child: CupertinoDatePicker(
                mode: CupertinoDatePickerMode.date, 
                onDateTimeChanged: (DateTime value) {
                  pickDate = value;
                },
              )
            )
          ],
        );
      }, context: context
    );
  }
  @override
  Widget build(BuildContext context) {
    Map<String, dynamic> props = widget.controlContext.mergedProps;
    // FormCreatorHandler formHandler = FormCreatorState.of(context);
    dynamic value = widget.controlContext.value == null ? null : DateTime.fromMillisecondsSinceEpoch(widget.controlContext.value);
    String dateFormatString = value == null ? props["placeholder"] : '${value.year}年${value.month}月${value.day}日';
    return ListItem(
      title: props["title"] ??= "日期选择",
      arrow: true,
      child: Text(dateFormatString, textAlign: TextAlign.end),
      onTap: ()  async {
        DateTime pickDate = await this._showDatePicker(context, value);
        _pickDate(pickDate);
      }
    );
  }
}